package com.company.project.common.advice;

import com.company.project.common.enums.RestCodeEnum;
import com.company.project.common.utils.RestUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.company.project.common.pojo.Rest;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;


/**
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Rest globalException(Exception e, HttpServletResponse response){
        //参数校验未通过异常 @RequestBody参数校验失败
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            List<ObjectError> errors = exception.getBindingResult().getAllErrors();
            StringBuffer sb = new StringBuffer();
            List<String> errorArr = Lists.newArrayList();
            for (ObjectError error : errors) {
                if (error instanceof FieldError){
                    FieldError fieldError=(FieldError)error;
                    errorArr.add(fieldError.getField()+fieldError.getDefaultMessage());
                }else{
                    errorArr.add(error.getObjectName()+error.getDefaultMessage());
                }
            }
            logger.info("参数错误：" + errorArr.toString());
            return RestUtil.rest(RestCodeEnum.CODE_400.getDesc(), "参数错误" , errorArr.toArray(new String[]{}));
        } else if (e instanceof ConstraintViolationException) {
            //@RequestParam 参数校验失败
            ConstraintViolationException exception = (ConstraintViolationException) e;
            List<String> errorArr = Lists.newArrayList();
            for (ConstraintViolation constraint : exception.getConstraintViolations()) {
                errorArr.add(constraint.getInvalidValue() + "非法" + constraint.getMessage());
            }
            logger.info("参数错误：" + errorArr.toString());
            return RestUtil.rest(RestCodeEnum.CODE_400.getCode(), "参数错误" , errorArr.toArray(new String[]{}));
        }else{
            e.printStackTrace();
            logger.error(e.getMessage());
            return RestUtil.rest(RestCodeEnum.CODE_500.getDesc(), "服务器错误", e.getMessage());
        }
    }

//    @ExceptionHandler(BindException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)//400
//    @ResponseBody
//    public Rest validateErrorHandler(BindException e) {
//        BindingResult bindingResult = e.getBindingResult();
//        if (bindingResult.hasErrors()) {
//            List<FieldError> errorList = e.getBindingResult().getFieldErrors();
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("field", errorList.get(0).getField());
//            map.put("errorMsg", errorList.get(0).getDefaultMessage());
//            logger.info(map.toString());
//            return RestUtil.rest(ServiceCode.CODE_403, "参数错误！！！" , map);
//        } else {
//        	e.printStackTrace();
//        	return RestUtil.rest(ServiceCode.CODE_500, "服务器错误");
//        }
//    }

    /**
     * Exception to be thrown when validation on an argument annotated with {@code @Valid} fails.
     */
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    @ResponseBody
//    public Rest handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
//        if (ex.getBindingResult().hasErrors()) {
//            List<FieldError> errorList = ex.getBindingResult().getFieldErrors();
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("field", errorList.get(0).getField());
//            map.put("errorMsg", errorList.get(0).getDefaultMessage());
//            logger.info(map.toString());
//            return RestUtil.rest(ServiceCode.CODE_403, "参数错误！！！" , map);
//        } else {
//        	ex.printStackTrace();
//        	return RestUtil.rest(ServiceCode.CODE_500, "服务器错误");
//        }
//    }

}